package org.byqh.dqeai.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.byqh.dqeai.common.Json;
import org.byqh.dqeai.dto.SysAppDatabaseDTO;
import org.byqh.dqeai.dto.common.IPage;
import org.byqh.dqeai.entity.SysAppDatabase;
import org.byqh.dqeai.entity.proxy.SysAppDatabaseProxy;
import org.byqh.dqeai.util.SpringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@RequestMapping("/appdb")
@Tag(name = "系统[SysAppDatabase] - 应用数据库管理")
public class SysAppDatabaseController extends BaseController<SysAppDatabase, SysAppDatabaseProxy> {

    @Override
    @PutMapping(value = "/put")
    public Json<Boolean> put(SysAppDatabase dto) {
        return super.put(dto);
    }

    @Override
    @PostMapping(value = "/post")
    public Json<Boolean> post(SysAppDatabase dto) {
        return super.post(dto);
    }

    @PostMapping(value = "/")
    public Json<Boolean> post(@RequestBody SysAppDatabaseDTO dto) {
        if (StringUtils.isBlank(dto.getDatabaseId())) {
            dto.setDatabaseId(UUID.randomUUID().toString());
        }

        if (dto.getPrimary() == null) {
            dto.setPrimary(false);
        }

        return this.save(dto);
    }

    @DeleteMapping(value = "/{id}")
    public Json<Boolean> delete(@PathVariable String id) {
        return this.removeById(id);
    }

    @PutMapping(value = "/")
    public Json<Boolean> put(@RequestBody SysAppDatabaseDTO dto) {
        var one = this.getEntityQueryable()
                .where(s -> s.databaseId().eq(dto.getDatabaseId()))
                .firstOrNull();

        if (one == null) {
            return Json.error("不存在要更改的数据", false, HttpStatus.OK.value());
        }

        BeanUtils.copyProperties(dto, one, SpringUtils.getNullPropertyNames(dto, "appId", "databaseId"));

        if (dto.getPrimary() == null) {
            dto.setPrimary(false);
        }

        return this.update(one);
    }

    /**
     * 查询应用对象信息列表
     */
    @PostMapping(value = "/list")
    public Json<IPage<SysAppDatabase>> list(@RequestParam(defaultValue = "1") Integer page,
                                            @RequestParam(defaultValue = "10") Integer size,
                                            @RequestParam(defaultValue = "", required = false) String sort,
                                            @RequestBody(required = false) SysAppDatabaseDTO dto) {
        return this.listPageImpl(SysAppDatabase.class, page, size, (query) -> {
            if (dto != null && !StringUtils.isBlank(dto.getAppId())) {
                query = query.where(r -> r.appId().eq(dto.getAppId()));
            }

            return query;
        });
    }
}